<template>
  <!-- 支付弹窗 -->
  <view :style="colorStyle">
    <view class="payment" :class="pay_close ? 'on' : ''">
      <view class="title acea-row row-center-wrapper">
        选择付款方式<text class="iconfont icon-guanbi" @click='close'></text>
      </view>
      <block v-if="combination_status">
        <view class="item acea-row row-between-wrapper">
          <!-- 开启组合支付 -->
          <view class="switchBox" >
            <text style="font-size: 30rpx;font-weight: bolder;">是否开启组合支付</text>
            <block v-if="switchHidden">
              <switch v-model="switchValue" checked  @change="onSwitchChange" />
            </block>
            <block v-else>
              <switch v-model="switchValue" @change="onSwitchChange" />
            </block>
          </view>
        </view>
      </block>
      <view class="item acea-row row-between-wrapper" v-for="(item,index) in payMode" :key="index"
           @click="payType(item.number || 0 , item.value,index)">
        <block  v-if='item.payStatus'>
          <view class="left acea-row row-between-wrapper">
            <view class="iconfont" :class="item.icon"></view>
            <view class="text">
              <view class="name">{{item.name}}</view>
              <view class="info" v-if="item.value == 'yue' ">
                {{item.title}} <span class="money">￥{{ item.number }}</span>
              </view>
              <view class="info" v-else>{{item.title}}</view>
              <view class="yueInput" v-if="item.value !== 'yue' && active==index  && switchValue==true && use_money >0" >余额支付:{{Number(use_money) }}</view>
            </view>
          </view>
          <view  class="iconfont" :class="active==index?'icon-xuanzhong11 font-num':'icon-weixuan'"></view>
        </block>

      </view>
      <!--组合支付金额展示模块      -->
      <view class="payMoney"  style="display: flex;justify-content: center; align-items: center; margin-top: 10rpx;">
        <view class="payMoney1">
          总价：<span class="font-color">¥<span
            class="money">{{totalPrice}}</span></span>
        </view>
        <view class="payMoney2" style="margin-left: 20rpx; text-align: left;" v-if="switchValue && use_money >0 && paytype!=='yue'">
          <view class="" >
            <span  style="font-size: 24rpx;">余额抵扣:</span>
            <span   class="font-color">¥<span
                class="money">{{use_money}}</span></span>
          </view>
          <view class="" v-if="(totalPrice-use_money)>0" >
            <span style="font-size: 24rpx;" > {{ paytype=='weixin' ? '微信支付' : paytype=='alipay' ? '支付宝支付' :  paytype=='allinpay' ? '银行卡支付' : '在线支付'}}</span>
            <span class="font-color">¥
						<span class="money">{{((Number(totalPrice)*100-Number(use_money)*100)/100).toFixed(2)}}</span></span>
          </view>
        </view>
      </view>

      <view class="button bg-color acea-row row-center-wrapper" @click='goPay(number, paytype,use_money)'>去付款</view>
      <slot name="buttom"></slot>
    </view>
    <view class="mask" @click='close' v-if="pay_close"></view>
    <view v-show="false" v-html="formContent"></view>
  </view>
</template>

<script>
import {
  orderPay
} from '@/api/order.js';
import colors from '@/mixins/color.js';
import {
  log
} from 'util';
export default {
  props: {
    payMode: {
      type: Array,
      default: function() {
        return [];
      }
    },
    pay_close: {
      type: Boolean,
      default: false,
    },
    order_id: {
      type: String,
      default: ''
    },
    totalPrice: {
      type: String,
      default: '0'
    },
    isCall: {
      type: Boolean,
      default: false
    },
    combination_status:{
      type: Boolean,
      default: true,
    },
  },
  mixins: [colors],
  data() {
    return {
      use_money: 0,
      minValue: 0,
      maxValue: 0,
      switchValue: true,
      formContent: '',
      active: 0,
      paytype: '',
      number: 0,
      switchHidden: true,     // 组合支付默认值  是否开启
    };
  },
  watch: {
    payMode: {
      handler(newV, oldValue) {
        let newPayList = [];
        newV.forEach((item, index) => {
          if (item.payStatus) {
            item.index = index;
            newPayList.push(item)
          }
        });
        this.active = newPayList[0].index;
        this.paytype = newPayList[0].value;
        this.number = newPayList[0].number || 0;
      },
      immediate: true,
      deep: true,
    },
    switchValue: {
      handler(newV, oldValue) {
        //开关打开给父组件传值，开关关闭值清空
        if (newV) {
          // console.log("开关打开",Number(this.totalPrice)-Number(this.totalPrice))
        } else {
          console.log('switchValue3333333333');
          //在开关关闭的时候 清空数据
          this.use_money = 0;
          this.$emit('changMoney', this.use_money)
        }
      },
      immediate: true,
      deep: true,
    }
  },
  methods: {
    //组合支付按钮状态切换
    onSwitchChange(e) {
      this.switchValue = e.detail.value;
      if (Number(this.payMode[0].number) > Number(this.totalPrice) || Number(this.payMode[0].number) == Number(this.totalPrice)) {
        this.use_money = this.totalPrice;
        this.maxValue = this.totalPrice;
      } else {
        this.use_money = this.payMode[0].number;
        this.maxValue = this.payMode[0].number;
      }
    },
    closeswitch(){
      this.switchHidden = false;
      this.switchValue = false;
    },
    //默认开启组合支付，仅调用一次
    openDefaultSwitch() {
      console.log('默认开启组合支付，仅调用一次 openDefaultSwitch')
      if (Number(this.payMode[0].number) > Number(this.totalPrice) || Number(this.payMode[0].number) == Number(this.totalPrice)) {
        this.use_money = this.totalPrice;
        this.maxValue = this.totalPrice;
      } else {
        this.use_money = this.payMode[0].number;
        this.maxValue = this.payMode[0].number;
      }
    },
    payTypeOnlyOne(number, paytype, index) {
      this.active = index;
      console.log(this.active,'this.active');
      this.paytype = paytype;
      this.number = number;
      this.$emit('changePayType', paytype, )
      if (this.switchValue) {
        this.$emit('changMoney', this.use_money)
      }
    },
    //默认开启组合支付，仅调用一次   end!!!!
    //支付方式切换  触发父组件方法
    payType(number, paytype, index) {
      this.active = index;
      console.log(this.active,'this.active');
      this.paytype = paytype;
      this.number = number;
      this.$emit('changePayType', paytype, )
      if (this.switchValue) {
        this.$emit('changMoney', this.use_money)
      }
    },
    close: function() {
      console.log('close===')
      this.$emit('onChangeFun', {
        action: 'payClose'
      });
    },
    goPay: function(number, paytype, use_money) {
      console.log("number1=", number, "paytype1=", paytype,"use_money== ",use_money)
      //存在iscall  执行回调不在向下执行，
      //不存在iscall  ，继续向下执行，无回调
      if (this.isCall) {
        return this.$emit('onChangeFun', {
          action: 'payCheck',
          value: paytype
        });
      }
      let that = this;
      console.log('payment that ==',that)
      if (!that.order_id) return that.$util.Tips({
        title: '请选择要支付的订单'
      });
      if (paytype == 'yue' && parseFloat(number) < parseFloat(that.totalPrice)) return that.$util.Tips({
        title: '余额不足！'
      });
      uni.showLoading({
        title: '支付中'
      });
      let obj = {
        uni: that.order_id,
        paytype: paytype,
        // #ifdef MP
        'from': 'routine',
        // #endif
        // #ifdef H5
        'from': this.$wechat.isWeixin() ? 'weixin' : 'weixinh5',
        // #endif
        // #ifdef H5
        quitUrl: location.port ? location.protocol + '//' + location.hostname + ':' + location
                .port +
            '/pages/goods/order_details/index?order_id=' + this.order_id : location.protocol +
            '//' + location.hostname +'/pages/goods/order_details/index?order_id=' + this.order_id
        // #endif
        // #ifdef APP-PLUS
        quitUrl: '/pages/goods/order_details/index?order_id=' + this.order_id
        // #endif
      }
      if (that.switchValue) {
        obj.use_money = use_money
      }
      if (!that.switchValue) {
        obj.use_money = ""
      }
      // #ifdef APP-PLUS
      if (paytype == 'allinpay') {
        plus.share.getServices(function(res) {
          var sweixin = null;
          for (var i = 0; i < res.length; i++) {
            var t = res[i];
            if (t.id == "weixin") {
              sweixin = t;
            }
          }
          if (sweixin) {
            sweixin.launchMiniProgram({
              // id: "gh_7b1957f6f62d", // 农购优选
              id: "gh_010ed55d9ce7",    //  农购网
              path: "pages/goods/PayDetail/index?uni=" + that.order_id,
              type: 0
            });
          }
        });
        setTimeout(res => {
          uni.redirectTo({
            url: "/pages/goods/order_list/index"
          })
        }, 3000)
        return false
        // return uni.navigateTo({
        // 	url: '/pages/goods/PayDetail/index?uni=' + that.order_id
        // })
      };
      // #endif
      console.log('去付款  传递的obj ',obj)
      orderPay(obj).then(res => {
        console.log('去付款 res ',res)
        let jsConfig = res.data.result.jsConfig;
        console.log('jsConfig== '.jsConfig)
        switch (paytype) {
          case 'weixin':
            if (res.data.result === undefined) return that.$util.Tips({
              title: '缺少支付参数'
            });
            // #ifdef MP
            let mp_pay_name = ''
            if (uni.requestOrderPayment) {
              mp_pay_name = 'requestOrderPayment'
            } else {
              mp_pay_name = 'requestPayment'
            }
            uni[mp_pay_name]({
              timeStamp: jsConfig.timestamp,
              nonceStr: jsConfig.nonceStr,
              package: jsConfig.package,
              signType: jsConfig.signType,
              paySign: jsConfig.paySign,
              success: function(res) {
                uni.hideLoading();
                return that.$util.Tips({
                  title: res.msg,
                  icon: 'success'
                }, () => {
                  that.$emit('onChangeFun', {
                    action: 'pay_complete'
                  });
                });
              },
              fail: function(e) {
                uni.hideLoading();
                return that.$util.Tips({
                  title: '取消支付'
                }, () => {
                  that.$emit('onChangeFun', {
                    action: 'pay_fail'
                  });
                });
              },
              complete: function(e) {
                uni.hideLoading();
                if (e.errMsg == 'requestPayment:cancel') return that.$util
                    .Tips({
                      title: '取消支付'
                    }, () => {
                      that.$emit('onChangeFun', {
                        action: 'pay_fail'
                      });
                    });
              },
            });
            // #endif
            // #ifdef H5
            let data = res.data;
            if (data.status == "WECHAT_H5_PAY") {
              uni.hideLoading();
              location.replace(data.result.jsConfig.mweb_url);
              return that.$util.Tips({
                title: "支付成功",
                icon: 'success'
              }, () => {
                that.$emit('onChangeFun', {
                  action: 'pay_complete'
                });
              });
            } else {
              that.$wechat.pay(data.result.jsConfig)
                  .then(() => {
                    return that.$util.Tips({
                      title: "支付成功",
                      icon: 'success'
                    }, () => {
                      that.$emit('onChangeFun', {
                        action: 'pay_complete'
                      });
                    });
                  })
                  .catch(function(res) {
                    if (res.errMsg == 'chooseWXPay:cancel') return that.$util.Tips({
                      title: '取消支付'
                    }, () => {
                      that.$emit('onChangeFun', {
                        action: 'pay_fail'
                      });
                    });
                  });
            }
            // #endif
            // #ifdef APP-PLUS
            uni.requestPayment({
              provider: 'wxpay',
              orderInfo: jsConfig,
              success: (e) => {
                let url = '/pages/goods/order_pay_status/index?order_id=' +
                    orderId +
                    '&msg=支付成功';
                uni.showToast({
                  title: "支付成功"
                })
                setTimeout(res => {
                  that.$emit('onChangeFun', {
                    action: 'pay_complete'
                  });
                }, 2000)
              },
              fail: (e) => {
                uni.showModal({
                  content: "支付失败",
                  showCancel: false,
                  success: function(res) {
                    if (res.confirm) {
                      that.$emit('onChangeFun', {
                        action: 'pay_fail'
                      });
                    } else if (res.cancel) {}
                  }
                })
              },
              complete: () => {
                uni.hideLoading();
              },
            });
            // #endif
            break;
          case 'yue':
            uni.hideLoading();
            return that.$util.Tips({
              title: res.msg,
              icon: 'success'
            }, () => {
              that.$emit('onChangeFun', {
                action: 'pay_complete'
              });
            });
            break;
          case 'offline':
            uni.hideLoading();
            return that.$util.Tips({
              title: res.msg,
              icon: 'success'
            }, () => {
              that.$emit('onChangeFun', {
                action: 'pay_complete'
              });
            });
            break;
          case 'alipay':
            uni.hideLoading();
            //#ifdef H5
            if (this.$wechat.isWeixin()) {
              uni.redirectTo({
                url: `/pages/users/alipay_invoke/index?id=${res.data.result.order_id}&pay_key=${res.data.result.pay_key}`
              });
            } else {
              uni.hideLoading();
              that.formContent = res.data.result.jsConfig;
              that.$nextTick(() => {
                document.getElementById('alipaysubmit').submit();
              });
            }
            //#endif
            // #ifdef MP
            uni.navigateTo({
              url: `/pages/users/alipay_invoke/index?id=${res.data.result.order_id}&link=${res.data.result.jsConfig.qrCode}`
            });
            // #endif
            // #ifdef APP-PLUS
            uni.requestPayment({
              provider: 'alipay',
              orderInfo: jsConfig,
              success: (e) => {
                uni.showToast({
                  title: "支付成功"
                })
                setTimeout(res => {
                  that.$emit('onChangeFun', {
                    action: 'pay_complete'
                  });
                }, 2000)

              },
              fail: (e) => {
                uni.showModal({
                  content: "支付失败",
                  showCancel: false,
                  success: function(res) {
                    if (res.confirm) {
                      that.$emit('onChangeFun', {
                        action: 'pay_fail'
                      });
                    } else if (res.cancel) {}
                  }
                })
              },
              complete: () => {
                uni.hideLoading();
              },
            });
            // #endif
            break;
          case 'allinpay':
            console.log("进入到通联支付")
            if (res.data.result === undefined) return that.$util.Tips({
              title: '缺少支付参数'
            });
            // #ifdef MP
            let mp_pay_name1 = ''
            if (uni.requestOrderPayment) {
              mp_pay_name1 = 'requestOrderPayment'
            } else {
              mp_pay_name1 = 'requestPayment'
            }
            uni[mp_pay_name1]({
              timeStamp: jsConfig.timeStamp,
              nonceStr: jsConfig.nonceStr,
              package: jsConfig.package,
              signType: jsConfig.signType,
              paySign: jsConfig.paySign,
              success: function(res) {
                uni.hideLoading();
                console.log("成功")
                return that.$util.Tips({
                  title: res.msg,
                  icon: 'success'
                }, () => {
                  that.$emit('onChangeFun', {
                    action: 'pay_complete'
                  });
                });
              },
              fail: function(e) {
                uni.hideLoading();
                console.log("失败")
                return that.$util.Tips({
                  title: '取消支付'
                }, () => {
                  that.$emit('onChangeFun', {
                    action: 'pay_fail'
                  });
                });
              },
              complete: function(e) {
                uni.hideLoading();
                console.log("最终", e)
                if (e.errMsg == 'requestPayment:cancel') return that.$util
                    .Tips({
                      title: '取消支付'
                    }, () => {
                      that.$emit('onChangeFun', {
                        action: 'pay_fail'
                      });
                    });
              },
            });
            // #endif
            // #ifdef H5
            let data1 = res.data;
            if (data1.status == "WECHAT_H5_PAY") {
              uni.hideLoading();
              location.replace(data1.result.jsConfig.mweb_url);
              return that.$util.Tips({
                title: "支付成功",
                icon: 'success'
              }, () => {
                that.$emit('onChangeFun', {
                  action: 'pay_complete'
                });
              });
            } else {
              that.$wechat.pay(data1.result.jsConfig)
                  .then(() => {
                    return that.$util.Tips({
                      title: "支付成功",
                      icon: 'success'
                    }, () => {
                      that.$emit('onChangeFun', {
                        action: 'pay_complete'
                      });
                    });
                  })
                  .catch(function(res) {
                    if (res.errMsg == 'chooseWXPay:cancel') return that.$util.Tips({
                      title: '取消支付'
                    }, () => {
                      that.$emit('onChangeFun', {
                        action: 'pay_fail'
                      });
                    });
                  });
            }
            // #endif
            // #ifdef APP-PLUS
            uni.requestPayment({
              provider: 'wxpay',
              orderInfo: jsConfig,
              success: (e) => {
                let url = '/pages/goods/order_pay_status/index?order_id=' +
                    orderId +
                    '&msg=支付成功';
                uni.showToast({
                  title: "支付成功"
                })
                setTimeout(res => {
                  that.$emit('onChangeFun', {
                    action: 'pay_complete'
                  });
                }, 2000)
              },
              fail: (e) => {
                uni.showModal({
                  content: "支付失败",
                  showCancel: false,
                  success: function(res) {
                    if (res.confirm) {
                      that.$emit('onChangeFun', {
                        action: 'pay_fail'
                      });
                    } else if (res.cancel) {}
                  }
                })
              },
              complete: () => {
                uni.hideLoading();
              },
            });
            // #endif
            break;
        }
      }).catch(err => {
        uni.hideLoading();
        return that.$util.Tips({
          title: err
        }, () => {
          that.$emit('onChangeFun', {
            action: 'pay_fail'
          });
        });
      })
    }
  }
}
</script>

<style scoped lang="scss">
.yueInput {
  width: 40%;
  height: 60rpx;
  padding-left: 10rpx;
  font-size: 30rpx;
  position: absolute;
  right: 0;
  bottom: 0;
  color: var(--view-theme);
}

.switchBox {
  padding-left: 20rpx;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.switchBox text {
  font-size: 30rpx;
  color: #282828;
}

.uni-switch-wrapper {
  border: 1px solid black;
}

.bgcolor {
  background-color: var(--view-theme)
}

.payment {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  border-radius: 16rpx 16rpx 0 0;
  background-color: #fff;
  padding-bottom: 60rpx;
  z-index: 999;
  transition: all 0.3s cubic-bezier(0.25, 0.5, 0.5, 0.9);
  transform: translate3d(0, 100%, 0);

  .payMoney {
    font-size: 28rpx;
    color: #333333;
    text-align: center;
    margin-top: 50rpx;

    .font-color {
      margin-left: 10rpx;

      .money {
        font-size: 40rpx;
      }
    }
  }

  .button {
    width: 690rpx;
    height: 90rpx;
    border-radius: 45rpx;
    color: #FFFFFF;
    margin: 20rpx auto 0 auto;
  }
}

.payment.on {
  transform: translate3d(0, 0, 0);
}

.payment .title {
  text-align: center;
  height: 123rpx;
  font-size: 32rpx;
  color: #282828;
  font-weight: bold;
  padding-right: 30rpx;
  margin-left: 30rpx;
  position: relative;
  border-bottom: 1rpx solid #eee;
}

.payment .title .iconfont {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 38rpx;
  color: #8a8a8a;
  font-weight: normal;
}

.payment .item {
  border-bottom: 1rpx solid #eee;
  height: 130rpx;
  margin-left: 30rpx;
  padding-right: 30rpx;
}

.payment .item .left {
  width: 610rpx;
}

.payment .item .left .text {
  width: 540rpx;
  position: relative;
}

.payment .item .left .text .name {
  font-size: 32rpx;
  color: #282828;
}

.payment .item .left .text .info {
  font-size: 24rpx;
  color: #999;
}

.payment .item .left .text .info .money {
  color: #ff9900;
}

.payment .item .left .iconfont {
  font-size: 45rpx;
  color: #09bb07;
}

.payment .item .left .iconfont.icon-zhifubao {
  color: #00aaea;
}

.payment .item .left .iconfont.icon-yuezhifu {
  color: #ff9900;
}

.payment .item .left .iconfont.icon-yuezhifu1 {
  color: #eb6623;
}

.payment .item .iconfont {
  font-size: 40rpx;
  color: #ccc;
}
</style>
